<template>

	<template v-for="(goodslist,shop) in cars" :key="shop">
		<view class="group">
			<view class="group_title">
				<view>店铺：{{shop}}</view>
			</view>

			<!-- 左滑删除组件 -->
			<uni-swipe-action>
				<uni-swipe-action-item v-for="(goods, index) in goodslist" :key="goods.skuId"
					:right-options="swipeOptions" @click="handleDelete(goods.skuId)">

					<view class="info" >
						<image :src="goods.isChecked==0?'/static/sel.png':'/static/unsel.png'" class="selimg"
							@click.stop="chg(goods)">
						</image>
						<image src="/static/a.jpg" class="goodsimg"></image>
						<view class="content">
							<view @click="gotoDetail(goods)">{{goods.skuName}}</view>
							<view class="price">
								<view class="small">￥</view>
								<view class="sale">{{goods.priceFee}}</view>
								<view class="small">.00</view>
							</view>
							<!-- 数量 -->
							<view class="num-container">
								<view>数量</view>
								<view class="num">
									<view :class="{'ena':goods.count>1, 'dis':goods.count==1}" @click="jian(goods)">-
									</view>
									<view class="numvalue">{{goods.count}}</view>
									<view class="ena" @click="add(goods)">+</view>
								</view>
							</view>
						</view>
					</view>
				</uni-swipe-action-item>
			</uni-swipe-action>
		</view>
	</template>

	<view style="height: 200rpx;"></view>


	<view v-if="Object.keys(cars).length === 0" class="empty-cart">
		购物车空空如也
	</view>


	<view class="btm">
		<view>
			<image :src="isSelectAll==0?'/static/sel.png':'/static/unsel.png'" class="selimg"
				style="margin-left: 15rpx;" @click="chgall"></image>
			<view>全选</view>
		</view>
		<view>
			<view style="color: #666;">
				总计:
			</view>
			<view>￥{{total}}</view>
		</view>
		<view class="js" @click="save">结算</view>
	</view>

	

</template>
<script>
	import {
		queryCar,
		updateNum,
		updateSel,
		deleteItem,
		allChecked
	} from '@/api/car.js'
	// 关键：手动导入左滑组件（解决组件未识别问题）
	import uniSwipeAction from '@dcloudio/uni-ui/lib/uni-swipe-action/uni-swipe-action.vue'
	import uniSwipeActionItem from '@dcloudio/uni-ui/lib/uni-swipe-action-item/uni-swipe-action-item.vue'
	import {
		saveOrder
	} from '@/api/order.js'
	import {onShow} from '@dcloudio/uni-app'
	export default {
		data() {
			return {
				//在该对象中声明的属性 都是响应式的  
				cars: {}, // 等同于 const cars=ref({});
				isSelectAll: 0, //默认全选
				// 左滑删除按钮配置（增加宽度确保可见）
				swipeOptions: [{
					text: '删除',
					style: {
						backgroundColor: '#ff3b30',
						width: '150rpx' // 按钮宽度，确保滑动后完整显示
					}
				}]
			}
		},
		// 关键：注册组件
		components: {
			uniSwipeAction,
			uniSwipeActionItem
		},
		methods: { //所有的方法在这里声明  
		   async save(){
			   let res=await saveOrder();
			   if(res.code==200){
				   //跳转订单详情
				   uni.navigateTo({
				   	url:"/pages/orderdetail/orderdetail?no="+res.data
				   })
			   }
		   },
			// 初始化购物车数据
			async init() {
				try {
					let res = await queryCar();
					console.log("接口响应:", res);
					// 确保即使 data 为空，cars 也是对象而非 undefined
					this.cars = res.data || {};

					this.chgAllStatus();
				} catch (err) {
					console.error("加载购物车失败:", err);
					this.cars = {}; // 失败时设为空对象
					uni.showToast({
						title: '加载失败',
						icon: 'none'
					});
				}
			},

			// 增加商品数量
			async add(goods) {
				let tmp = goods.count + 1;
				let data = {
					skuId: goods.skuId,
					count: tmp
				};
				let res = await updateNum(data);
				if (res.code == 200) {
					goods.count = tmp;
				}
			},

			// 减少商品数量
			async jian(goods) {
				let tmp = goods.count;
				if (tmp == 1) return;

				let data = {
					skuId: goods.skuId,
					count: --tmp
				};
				let res = await updateNum(data);
				if (res.code == 200) {
					goods.count = tmp;
				}
			},

			// 切换商品选中状态
			async chg(goods) {
				let res = await updateSel(goods.skuId);
				if (res.code == 200) {
					goods.isChecked = goods.isChecked == 0 ? 1 : 0;
					this.chgAllStatus();
				}
			},

			// 左滑删除商品
			async handleDelete(skuId) {
				// 只需要 skuId 即可删除
				try {
					// 显示确认框
					const {
						confirm
					} = await uni.showModal({
						title: '提示',
						content: '确定要删除该商品吗？'
					});

					if (confirm) {
						// 调用删除接口（只传 skuId）
						const res = await deleteItem(skuId);
						if (res.code === 200) {
							uni.showToast({
								title: '删除成功',
								icon: 'success'
							});
							this.init(); // 重新调用初始化方法，从接口拉取最新数据
						} else {
							uni.showToast({
								title: '删除失败',
								icon: 'none'
							});
						}
					}
				} catch (error) {
					console.error('删除出错：', error);
					uni.showToast({
						title: '删除失败',
						icon: 'none'
					});
				}
			},
			//点击进入商品详情页
			async gotoDetail(goods) {
				const id = goods.spuId || goods.skuId;
				console.log("跳转商品详情页 id:" + id);
				uni.navigateTo({
					url: `/pages/goodsdetail/goodsdetail?id=${id}`
				});
			},

			// 更新全选状态
			chgAllStatus() {
				// 1. 购物车空，直接未选中
				if (Object.keys(this.cars).length === 0) {
					this.isSelectAll = 1;
					return;
				}

				let allSelected = true;

				for (let shop in this.cars) {
					const hasUnselected = this.cars[shop].some(goods => goods.isChecked !== 0);
					if (hasUnselected) {
						allSelected = false;
						break;
					}
				}

				this.isSelectAll = allSelected ? 0 : 1;
			},

			// 全选/取消全选
			async chgall() {
				// 1. 确定要传给接口的参数：当前是全选（isSelectAll=0）则传1（取消全选），反之传0（全选）
				const reqParam = this.isSelectAll === 0 ? 1 : 0;

				try {
					// 2. 调用全选接口，传参数（0=全选，1=全不选）
					const res = await allChecked(reqParam);

					if (res.code === 200) {
						// 3. 接口成功后，更新页面全选状态和商品选中状态
						this.isSelectAll = reqParam; // 同步全选按钮状态（接口传1则页面设为1，即全不选）

						// 4. 同步所有商品的选中状态（与全选状态一致）
						for (let shop in this.cars) {
							const goodsList = this.cars[shop];
							goodsList.forEach(goods => {
								goods.isChecked = this.isSelectAll; // 商品选中状态 = 全选状态
							});
						}
					} else {
						// 接口失败提示
						uni.showToast({
							title: '操作失败',
							icon: 'none'
						});
					}
				} catch (error) {
					// 捕获请求异常
					console.error('全选接口调用失败：', error);
					uni.showToast({
						title: '网络错误，操作失败',
						icon: 'none'
					});
				}
			}
			
		},
		computed: {
			//计算属性  计算总价格 
			total() {
				let t = 0;
				for (let o in this.cars) { //o是对象cars中的属性名（这里对应的是店铺）
					//获取当前店铺下的购物列表
					let tmplist = this.cars[o];
					//遍历列表
					for (let i = 0, len = tmplist.length; i < len; i++) {
						//获取当前 商品
						let goods = tmplist[i];
						//判断当前商品是否选中
						if (goods.isChecked == 0) { //选中 参与价格计算
							//价格
							let price = parseFloat(goods.priceFee);
							//数量
							let num = parseInt(goods.count);
							t += num * price;
						}
					}
				}
				return t;
			}
		},
		onShow(){
			this.init()
		}
	}
</script>

<style scoped>
	.pay {
		width: 720rpx;
		height: 500rpx;
		border: #d81e06 solid 1px;

	}

	/* 解决左滑组件样式冲突 */
	uni-swipe-action {
		width: 100%;
		/* 确保组件占满宽度，滑动区域有效 */
	}

	/* 空购物车样式 */
	.empty-cart {
		text-align: center;
		padding: 200rpx 0;
		color: #999;
		font-size: 32rpx;
	}


	.btm {
		width: 750rpx;
		height: 100rpx;
		background-color: #fff;
		position: fixed;
		left: 0;
		bottom: 100rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.btm>view {
		display: flex;
	}

	.js {
		width: 150rpx;
		background-color: #d81e06;
		border-radius: 3px;
		color: #fff;
		height: 70rpx;
		line-height: 70rpx;
		margin-right: 15rpx;
		text-align: center;
		display: flex;
		justify-content: center;
	}

	.num {
		display: flex;
	}

	/* 数量控制 */
	.num {
		display: flex;
	}

	.dis {
		display: inline-block;
		width: 50rpx;
		height: 50rpx;
		line-height: 50rpx;
		text-align: center;
		margin-right: 5px;
		color: #999;
		font-size: 18px;
	}

	.ena {
		display: inline-block;
		width: 50rpx;
		height: 50rpx;
		line-height: 50rpx;
		text-align: center;
		color: #000;
		margin-left: 5px;
		font-size: 18px;
	}

	.numvalue {
		padding: 0 15px;
		background-color: #eee;
	}

	.num-container {
		display: flex;
		justify-content: space-between;
		height: 60rpx;
		line-height: 60rpx;
	}


	/* 商品内容 */
	.content {
		display: flex;
		flex-direction: column;
		margin-left: 10px;
		width: 460rpx;
	}

	.group {
		width: 750rpx;
		border-radius: 10px;
		background-color: #fff;
		padding: 20px 0;
		margin-top: 10px;
	}

	.group_title {
		display: flex;
		width: 720rpx;
		margin: auto;
	}

	.selimg {
		width: 50rpx;
		height: 50rpx;
		margin-right: 20rpx;
	}

	.goodsimg {
		width: 150rpx;
		height: 150rpx;
		border-radius: 6px;
	}

	/* 商品项容器（关键：加背景色避免左滑露空白） */
	.info {
		display: flex;
		align-items: center;
		width: 720rpx;
		margin: auto;
		margin-top: 10px;
		background-color: #fff;
		/* 与group背景一致 */
	}

	.price {
		color: #d81e06;
		display: flex;
		align-items: baseline;
		font-weight: bold;
	}

	.sale {
		font-size: 16px;
	}

	.small {
		font-size: 10px;
	}
</style>
